package com.wzl.backend.util;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;

public class FileUtil {

//    public static final String BASE_RESOURCES_PATH = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources"
//            + File.separator + "static" + File.separator + "head_icon" + File.separator;
    public static final String BASE_RESOURCES_PATH = "/www/static/";

    public static void copyIcon(String sourceFileName , String targetFileName) throws IOException {
        String base = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator +  "static" + File.separator + "head_icon" + File.separator;
        File source = new File(base + sourceFileName);
        File target = new File(base + targetFileName);
        Files.copy(source.toPath() , target.toPath());
    }

    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        try (InputStream input = Files.newInputStream(source.toPath()); OutputStream output = Files.newOutputStream(dest.toPath())) {
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        }
    }


    //返回上级目录
    public static File returnBackPath(File file) {
        File newFile = new File(returnBackPath(file.getPath()));
        return newFile;
    }

    //返回上级目录
    public static String returnBackPath(String path) {
        StringBuilder sb = new StringBuilder();
        sb.append(path);
        StringBuilder reverse = sb.reverse();
        for (int i = 0 ; i < reverse.length() ; i++) {
            if (reverse.charAt(i) == '\\') {
                sb = new StringBuilder();
                sb.append(reverse.substring(i +1 , path.length()));
                sb.append('\\');
                break;
            }
        }
        return sb.reverse().toString();
    }

    public String lastName(File file) {
        if (file == null) return null;
        String filename = file.getName();
        // split用的是正则，所以需要用 //. 来做分隔符
        String[] split = filename.split("\\.");
        //注意判断截取后的数组长度，数组最后一个元素是后缀名
        if (split.length > 1) {
            return split[split.length - 1];
        } else {
            return "";
        }
    }

}
